import os
from pathlib import Path
from typing import Any, Dict

import yaml


class Settings:
    """配置管理类"""

    def __init__(self):
        self.config = self._load_config()
        # 在初始化时就设置环境变量，确保后续导入的模块能使用正确的配置
        self._setup_environment_variables()

    def _load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        config_path = Path(__file__).parent / "config.yaml"

        # 加载YAML配置文件
        with open(config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)

        # 环境变量覆盖配置
        self._override_with_env(config)

        return config

    # 正确的静态方法实现
    @staticmethod
    def _override_with_env(config: Dict[str, Any]):
        """使用环境变量覆盖配置"""
        # 服务器配置
        config['server']['host'] = os.getenv('HOST', config['server']['host'])
        config['server']['port'] = int(os.getenv('PORT', config['server']['port']))
        config['server']['workers'] = int(os.getenv('WORKERS', config['server']['workers']))
        config['server']['threads'] = int(os.getenv('THREADS', config['server']['threads']))
        config['server']['limit_concurrency'] = int(
            os.getenv('LIMIT_CONCURRENCY', config['server']['limit_concurrency']))

        # 开发模式开关
        config['app']['dev'] = os.getenv('dev', str(config['app']['dev'])).lower() == 'true'
        # TODO 将配置文件config.yaml信息,读取信息后放入环境os变量中

    def _setup_environment_variables(self):
        """早期初始化环境变量，确保所有后续导入的模块都能使用正确的配置"""
        # 设置Paddle相关的环境变量
        model_cache_dir = self.config['paddle'].get('model_cache_dir')
        os.environ.setdefault('PADDLE_PDX_CACHE_HOME', model_cache_dir)
        paddle_pdx_model_source = self.config['paddle'].get('paddle_pdx_model_source')
        os.environ.setdefault('PADDLE_PDX_MODEL_SOURCE', paddle_pdx_model_source)

        # 设置USE_GPU环境变量
        # TODO 逻辑为: 如果使用GPU，则设置CUDA_VISIBLE_DEVICES环境变量为GPU ID，否则设置为-1,使用CPU
        if str(self.config['paddle']['use_gpu']).lower() == 'true':
            gpu_id = self.config['paddle'].get('gpu_id', '0')
            os.environ.setdefault('CUDA_VISIBLE_DEVICES', gpu_id)
            os.environ.setdefault('FLAGS_cudnn_deterministic', 'True')
            os.environ.setdefault('FLAGS_eager_delete_tensor_gb', '0')
            os.environ.setdefault('FLAGS_fraction_of_gpu_memory_to_use', '0.98')
            os.environ.setdefault('FLAGS_sync_nccl_allreduce', 'True')
        else:
            os.environ.setdefault('CUDA_VISIBLE_DEVICES', '-1')
            os.environ.setdefault('FLAGS_sync_nccl_allreduce', 'False')
            os.environ.setdefault('FLAGS_fast_eager_deletion_mode', 'True')
            os.environ.setdefault('FLAGS_memory_fraction_of_eager_deletion', '1.0')
            os.environ.setdefault('FLAGS_eager_delete_tensor_gb', '0')
        # 添加调试信息
        # print(f"[DEBUG] 调试信息 PADDLE_PDX_CACHE_HOME={os.getenv('PADDLE_PDX_CACHE_HOME')}")

    def get(self, key_path: str, default: Any = None) -> Any:
        """获取配置值，支持点号分隔路径"""
        keys = key_path.split('.')
        value = self.config

        try:
            for key in keys:
                value = value[key]
            return value
        except (KeyError, TypeError):
            return default


# 全局配置实例
settings = Settings()
